package com.dz.lm.service.usermessage.impl;

import com.dz.lm.common.dto.PageDto;
import com.dz.lm.common.dto.UserMessageDTO;
import com.dz.lm.common.dto.UserMessageRecordDTO;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.dao.appLogin.read.AppLoginDao;
import com.dz.lm.dao.usermessage.read.UserMessageDao;
import com.dz.lm.dao.usermessagerecord.write.UserMessageRecordDao;
import com.dz.lm.domain.usermessage.UserMessage;
import com.dz.lm.domain.usermessage.UserMessageExample;
import com.dz.lm.service.usermessage.UserMessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.dz.lm.domain.usermessagerecord.UserMessageRecord;
import com.dz.lm.domain.usermessagerecord.UserMessageRecordExample;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @version 1.8;
 * @author: LDY;
 * @Description;
 * @Date: Created in 2020/6/29 10:53;
 */
@Service
public class UserMessageServiceImpl implements UserMessageService {
    private static final Logger logger = LoggerFactory.getLogger(UserMessageServiceImpl.class);

    @Resource(name = "readUserMessageDao")
    private UserMessageDao readUserMessageDao;
    @Resource(name = "writeUserMessageDao")
    private com.dz.lm.dao.usermessage.write.UserMessageDao writeUserMessageDao;
    @Resource(name = "writeUserMessageRecordDao")
    private UserMessageRecordDao writeUserMessageRecordDao;
    @Resource(name = "readUserMessageRecordDao")
    private com.dz.lm.dao.usermessagerecord.read.UserMessageRecordDao readUserMessageRecordDao;
    @Resource(name = "readAppLoginDao")
    private AppLoginDao rAppLoginDao;

    @Override
    @Transactional
    public int add(UserMessage userMessage) throws ServiceException {
        int ret = 0;
        try {
            ret = writeUserMessageDao.insertSelective(userMessage);
            if(ret > 0){//添加联系人列表
                UserMessageRecordExample ex1 = new UserMessageRecordExample();
                UserMessageRecordExample.Criteria c1 = ex1.createCriteria();
                c1.andSessionIdEqualTo(userMessage.getUserId()+"-"+userMessage.getSendUid());
                int i = readUserMessageRecordDao.queryCount(ex1);
                if(i>0){
                    UserMessageRecord r1 = new UserMessageRecord();
                    r1.setSessionId(userMessage.getUserId()+"-"+userMessage.getSendUid());
                    r1.setCreateTime(DateUtil.getTimeStr(new Date()));
                    r1.setStatus(1);
                    r1.setMessage(userMessage.getMessage());
                    writeUserMessageRecordDao.updateByPrimaryKeySelective(r1);
                }else {
                    UserMessageRecord r1 = new UserMessageRecord();
                    r1.setSessionId(userMessage.getUserId()+"-"+userMessage.getSendUid());
                    r1.setCreateTime(DateUtil.getTimeStr(new Date()));
                    r1.setStatus(1);
                    r1.setUserId(userMessage.getUserId());
                    r1.setSendUid(userMessage.getSendUid());
                    r1.setMessage(userMessage.getMessage());
                    writeUserMessageRecordDao.insertSelective(r1);
                }

                UserMessageRecordExample ex2 = new UserMessageRecordExample();
                UserMessageRecordExample.Criteria c2 = ex2.createCriteria();
                c1.andSessionIdEqualTo(userMessage.getSendUid()+"-"+userMessage.getUserId());
                int i1 = readUserMessageRecordDao.queryCount(ex2);
                if(i1>0){
                    UserMessageRecord r2 = new UserMessageRecord();
                    r2.setSessionId(userMessage.getSendUid()+"-"+userMessage.getUserId());
                    r2.setCreateTime(DateUtil.getTimeStr(new Date()));
                    r2.setStatus(1);
                    r2.setMessage(userMessage.getMessage());
                    writeUserMessageRecordDao.updateByPrimaryKeySelective(r2);
                }else {
                    UserMessageRecord r2 = new UserMessageRecord();
                    r2.setSessionId(userMessage.getSendUid()+"-"+userMessage.getUserId());
                    r2.setCreateTime(DateUtil.getTimeStr(new Date()));
                    r2.setStatus(1);
                    r2.setUserId(userMessage.getSendUid());
                    r2.setSendUid(userMessage.getUserId());
                    r2.setMessage(userMessage.getMessage());
                    writeUserMessageRecordDao.insertSelective(r2);
                }
            }
        } catch (DaoException e) {
            throw new ServiceException(e, logger);
        }
        return ret;
    }

    @Override
    @Transactional
    public int deleteByUser(int recordId) throws ServiceException {
        int ret = 0;
        try {
            ret=  writeUserMessageRecordDao.deleteByPrimaryKey(recordId);
        } catch (DaoException e) {
            throw new ServiceException(e, logger);
        }
        return ret;
    }

    @Override
    public PageDto query(int pageNum, int rows, int uid) throws ServiceException {
        PageDto page = new PageDto();
        PageHelper.startPage(pageNum, rows);
        try {
            UserMessageRecordExample ex = new UserMessageRecordExample();
            ex.setOrderByClause("status desc,create_time desc");
            UserMessageRecordExample.Criteria cr = ex.createCriteria();
            cr.andUserIdEqualTo(uid);
            List<UserMessageRecord> list = readUserMessageRecordDao.selectByExample(ex);
            if (list != null && list.size() > 0) {
                PageInfo pageInfo = new PageInfo(list);
                Map p1 = new HashMap();
                List<UserMessageRecordDTO> dtos = new ArrayList();
                for (UserMessageRecord record : list) {
                    UserMessageRecordDTO dto = new UserMessageRecordDTO();
                    BeanUtils.copyProperties(record,dto);
                    p1.clear();
                    p1.put("userId", record.getSendUid());
                    Map user = rAppLoginDao.qryUserInfoByUserId(p1);
                    if(user != null){
                        dto.setSendUser(user);
                    }
                    dtos.add(dto);
                }
                page.setList(dtos);
                page.setInfo(pageInfo);
            }
        } catch (DaoException e) {
            throw new ServiceException(e, logger);
        }
        return page;
    }

    @Override
    @Transactional
    public PageDto getDetail(int pageNum, int rows, int uid, int userId) throws ServiceException {
        this.updateStatus(uid,userId);
        PageHelper.startPage(pageNum,rows);
        PageDto pageDto = new PageDto();
        UserMessageExample ex = new UserMessageExample();
        ex.setOrderByClause("create_time desc");
        UserMessageExample.Criteria cr = ex.createCriteria();
        cr.andUserIdEqualTo(uid);
        cr.andSendUidEqualTo(userId);
        UserMessageExample.Criteria cr1 = ex.createCriteria();
        cr1.andUserIdEqualTo(userId);
        cr1.andSendUidEqualTo(uid);
        ex.or(cr1);
        try {
            List<UserMessage> list = readUserMessageDao.selectByExample(ex);
            if(list != null && list.size() >0){
                PageInfo pageInfo = new PageInfo(list);
                List<UserMessageDTO> dtos = new ArrayList();
                for (UserMessage message : list) {
                    UserMessageDTO dto = new UserMessageDTO();
                    BeanUtils.copyProperties(message,dto);
                    Map p1 = new HashMap();
                    p1.put("userId",message.getUserId());
                    Map user = rAppLoginDao.qryUserInfoByUserId(p1);
                    if(user != null){
                        dto.setUser(user);
                    }
                    p1.clear();
                    p1.put("userId",message.getSendUid());
                    Map sendUser = rAppLoginDao.qryUserInfoByUserId(p1);
                    if(sendUser != null){
                        dto.setSendUser(sendUser);
                    }
                    if(message.getSendUid() == userId){
                        dto.setFlag(1);
                    }
                    dtos.add(dto);
                }
                pageDto.setInfo(pageInfo);
                pageDto.setList(dtos);
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }

        return pageDto;
    }

    @Override
    @Transactional
    public int updateStatus(int uid, int sendUid) throws ServiceException {
        int ret = 0;
        try {
            UserMessageRecord record = new UserMessageRecord();
            record.setSessionId(uid+"-"+sendUid);
            record.setStatus(0);
            ret = writeUserMessageRecordDao.updateByPrimaryKeySelective(record);
        } catch (DaoException e) {
            throw new ServiceException(e, logger);
        }
        return ret;
    }

    @Override
    public int getCount(int uid) throws ServiceException {
        int ret =0;
        UserMessageRecordExample ex = new UserMessageRecordExample();
        UserMessageRecordExample.Criteria cr = ex.createCriteria();
        cr.andUserIdEqualTo(uid);
        cr.andStatusEqualTo(1);
        try {
            ret = readUserMessageRecordDao.queryCount(ex);
        } catch (DaoException e) {
            e.printStackTrace();
        }

        return ret;
    }
}
